package com.jinzhi.eventresource.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.eventresource.main.EventresourceAllocationsDO;
import com.jinzhi.eventresource.main.TemplateCertificateDO;
import com.jinzhi.eventresource.service.EventresourceAllocationsService;
import com.jinzhi.eventresource.service.TemplateCertificateService;
import com.jinzhi.eventresource.vo.TemplateVO.CertificateVO;
import com.jinzhi.eventresource.vo.TemplateVO.TemplateCertificateVO;
import com.jinzhi.eventresource.vo.TemplateVO.TestPaperTemplateVO;
import com.jinzhi.jzweb.domain.CertificateNewsDO;
import com.jinzhi.jzweb.domain.CertificateProfileDO;
import com.jinzhi.jzweb.domain.TemplateDetailsDO;
import com.jinzhi.jzweb.domain.TestPaperTemplateDO;
import com.jinzhi.jzweb.domain.modelConfig.PageInfo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Controller
@RequestMapping("/jzweb/eventResourceTemplate")
public class TemplateController extends BaseController {
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private UserService userService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private TemplateCertificateService templateCertificateService;
    @Autowired
    private TemplateDetailsService templateDetailsService;
    @Autowired
    private EventresourceAllocationsService eventresourceAllocationsService;

    @GetMapping()
    @RequiresPermissions("jzweb:templateController:templateController")
    String templateController() {
        return "jzweb/templateController/templateController";
    }

    @GetMapping("/getCertificateList")
    @ResponseBody
    public Result<List<CertificateNewsDO>> getCertificateList() {
//        List<CertificateProfileDO> certificateProfileDOS = certificateProfileService.selectList(new EntityWrapper<>());
        List<CertificateNewsDO> certificateNewsDOS = certificateNewsService.selectList(new EntityWrapper<>());

        for (CertificateNewsDO certificateNewsDO : certificateNewsDOS) {
            CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(certificateNewsDO.getProfileId());
            String name = certificateProfileDO.getName();
            if (certificateNewsDO.getGrade() == 0) {
                name = name + " (高级)";
            } else if (certificateNewsDO.getGrade() == 1) {
                name = name + " (中级)";
            } else if (certificateNewsDO.getGrade() == 2) {
                name = name + " (初级)";
            }
            certificateNewsDO.setProfileName(name);
        }

        return Result.ok(certificateNewsDOS);
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:templateController:templateController")
    public Result<Page<TestPaperTemplateVO>> list(TemplateCertificateVO templateCertificateVO) {
        // 根据关联表列出所有模板信息
        EntityWrapper<TemplateCertificateDO> wrapper = new EntityWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(templateCertificateVO.getName()), "name", templateCertificateVO.getName());
        wrapper.like(ObjectUtil.isNotEmpty(templateCertificateVO.getName()), "newsName", templateCertificateVO.getName());
        wrapper.eq(ObjectUtil.isNotEmpty(templateCertificateVO.getType()), "type", templateCertificateVO.getType());
        wrapper.eq(ObjectUtil.isNotEmpty(templateCertificateVO.getState()), "state", templateCertificateVO.getState());
        // 分页
        List<TemplateCertificateDO> templateCertificateDOList = templateCertificateService.selectList(wrapper);

        List<TestPaperTemplateDO> testPaperTemplateDOList = templateCertificateDOList.stream().map(templateCertificateDO -> {
            Long paperTemplateId = templateCertificateDO.getPaperTemplateId();
            TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.selectById(paperTemplateId);
            List<TemplateCertificateDO> templateCertificateDOS = templateCertificateService.selectList(new EntityWrapper<TemplateCertificateDO>()
                    .eq("paper_template_id", templateCertificateDO.getPaperTemplateId())
                    .eq("state", templateCertificateDO.getState()));

            // 证书id 证书 名称
            List<CertificateVO> certificateVOList = templateCertificateDOS.stream().map(templateCertificateDO1 -> {
                CertificateNewsDO certificateNewsDO = certificateNewsService.selectOne(new EntityWrapper<CertificateNewsDO>()
                        .eq("id", templateCertificateDO1.getCertificateNewsId()));
                return new CertificateVO(templateCertificateDO1.getNewsName(), templateCertificateDO1.getCertificateNewsId(), certificateNewsDO);
            }).collect(Collectors.toList());

            testPaperTemplateDO.setCertificateVOList(certificateVOList);
            return testPaperTemplateDO;
        }).sorted(Comparator.comparing(TestPaperTemplateDO::getId)).distinct().collect(Collectors.toList());

        List<TestPaperTemplateVO> collect = testPaperTemplateDOList.stream().map(testPaperTemplateDO -> {
            TestPaperTemplateVO testPaperTemplateVO = new TestPaperTemplateVO();
            BeanUtils.copyProperties(testPaperTemplateDO, testPaperTemplateVO);
            String name = userService.selectById(testPaperTemplateDO.getCreaterId()).getUsername();
            testPaperTemplateVO.setCreaterName(name);
            return testPaperTemplateVO;
        }).collect(Collectors.toList());
        // 不写sql是这样的^_^
        collect.sort(Comparator.comparing(TestPaperTemplateVO::getCreaterDate).reversed());
        List<TestPaperTemplateVO> pageResult = collect.stream()
                .skip((templateCertificateVO.getCurrent() - 1) * templateCertificateVO.getSize())
                .limit(templateCertificateVO.getSize())
                .collect(Collectors.toList());

        Page<TestPaperTemplateVO> testPaperTemplateVOPage = new Page<>();
        testPaperTemplateVOPage.setRecords(pageResult);
        testPaperTemplateVOPage.setCurrent(templateCertificateVO.getCurrent());
        testPaperTemplateVOPage.setTotal(collect.size());

        return Result.ok(testPaperTemplateVOPage);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:templateController:add")
    String add(Model model) {
        model.addAttribute("certificateProfile", certificateNewsService.selByNewId());
        return "jzweb/templateController/add";
    }

    /**
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:templateController:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.selectById(id);

        // 获取试卷相关证书
        List<TemplateCertificateDO> templateCertificateDOS = templateCertificateService
                .selectList(new EntityWrapper<TemplateCertificateDO>().eq("paper_template_id", testPaperTemplateDO.getId()));
        List<String> certificateNewsId = templateCertificateDOS.stream()
                .map(templateCertificateDO -> templateCertificateDO.getCertificateNewsId().toString()).collect(Collectors.toList());

        //
        TestPaperTemplateVO testPaperTemplate = new TestPaperTemplateVO();
        BeanUtils.copyProperties(testPaperTemplateDO, testPaperTemplate);

        String newsId = certificateNewsId.get(0);
        // 前端字符串证书id 显示
        for (int i = 1; i < certificateNewsId.size(); i++) {
            newsId = newsId + "," + certificateNewsId.get(i);
        }

        // 根据证书id获取证书信息
        List<CertificateVO> certificateNewsDOList = certificateNewsId.stream().map(cerId -> {
            CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(cerId);
            CertificateVO certificateVO = new CertificateVO();
            certificateVO.setNewsList(certificateNewsDO);
            certificateVO.setTitle(certificateProfileService.selectById(certificateNewsDO.getProfileId()).getName());
            certificateVO.setValue(certificateNewsDO.getId());
            return certificateVO;
        }).collect(Collectors.toList());

        testPaperTemplateDO.setCertificateVOList(certificateNewsDOList);

        testPaperTemplate.setNewsIsStringList(newsId);
        System.out.println(newsId);
        model.addAttribute("testPaperTemplate", testPaperTemplate);

        return "jzweb/templateController/edit";
    }

    @Log("添加试卷模板")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:templateController:add")
    public Result<String> save(@RequestBody TemplateCertificateVO templateCertificateVO) {
        templateCertificateVO.setState(0);

        Boolean success = true;
        // 新增模板
        TestPaperTemplateDO testPaperTemplateDO = new TestPaperTemplateDO();
        BeanUtils.copyProperties(templateCertificateVO, testPaperTemplateDO);
        // 状态 创建人姓名和id 时间
        testPaperTemplateDO.setState(0);
        testPaperTemplateDO.setCreaterId(getUserId());
        testPaperTemplateDO.setType(templateCertificateVO.getType());
        testPaperTemplateDO.setCreaterId(getUserId());
        testPaperTemplateDO.setCreaterDate(DateTime.now());
        success = testPaperTemplateService.insert(testPaperTemplateDO);
        templateCertificateVO.setPaperTemplateId(testPaperTemplateDO.getId());

        // 新增关联表
        List<CertificateVO> newsIdList = templateCertificateVO.getNewsIdList();
        for (CertificateVO certificateVO : newsIdList) {
            Long newsId = certificateVO.getValue();
            TemplateCertificateDO templateCertificateDO = new TemplateCertificateDO();
            templateCertificateDO.setPaperTemplateId(templateCertificateVO.getPaperTemplateId());
            Long newId = Long.valueOf(newsId);
            templateCertificateDO.setCertificateNewsId(newId);
            // name试卷模板名称 newsName type state
            templateCertificateDO.setState(0);
            templateCertificateDO.setType(templateCertificateVO.getType());
            templateCertificateDO.setNewsName(certificateVO.getNewsList().getProfileName());
            templateCertificateDO.setName(templateCertificateVO.getName());

            success = templateCertificateService.insert(templateCertificateDO);
        }

        return success ? Result.ok() : Result.fail("新增失败");
    }

    @Log("修改试卷模板关联")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("jzweb:templateController:edit")
    public Result<Boolean> update(@RequestBody TemplateCertificateVO templateCertificateVO) {
        // 判断是否重复关联
        EntityWrapper<TemplateCertificateDO> templateCertificateDOWrapper = new EntityWrapper<>();
        templateCertificateDOWrapper.eq("paper_template_id", templateCertificateVO.getPaperTemplateId());
        List<TemplateCertificateDO> templateCertificateDOList = templateCertificateService.selectList(templateCertificateDOWrapper);

        // 删除关联表
        templateCertificateService.deleteBatchIds(templateCertificateDOList.stream()
                .map(TemplateCertificateDO::getId).collect(Collectors.toList()));
        // 删除模板详情信息
        EntityWrapper<TemplateDetailsDO> deleteWrapper = new EntityWrapper<>();
        deleteWrapper.eq("tptemplate_id", templateCertificateVO.getPaperTemplateId());
        templateDetailsService.delete(deleteWrapper);

        // 新增
        List<CertificateVO> newsIdList = templateCertificateVO.getNewsIdList();
        for (CertificateVO certificateVO : newsIdList) {
            Long newsId = certificateVO.getValue();
            TemplateCertificateDO templateCertificateDO = new TemplateCertificateDO();
            templateCertificateDO.setPaperTemplateId(templateCertificateVO.getPaperTemplateId());
            Long newId = Long.valueOf(newsId);
            templateCertificateDO.setCertificateNewsId(newId);
            // name试卷模板名称 newsName type state
            templateCertificateDO.setState(0);
            templateCertificateDO.setType(templateCertificateVO.getType());
            templateCertificateDO.setNewsName(certificateVO.getNewsList().getProfileName());
            templateCertificateDO.setName(templateCertificateVO.getName());

            templateCertificateService.insert(templateCertificateDO);
        }

        // 修改试卷模板信息
        TestPaperTemplateDO testPaperTemplateDO = new TestPaperTemplateDO();
        BeanUtils.copyProperties(templateCertificateVO, testPaperTemplateDO);
        testPaperTemplateDO.setId(templateCertificateVO.getPaperTemplateId());
        testPaperTemplateService.updateById(testPaperTemplateDO);

        return Result.ok();
    }

    @Log("删除试卷模板证书关联")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:templateController:remove")
    public Result<Boolean> remove(String paperTemplateId) {
        List<EventresourceAllocationsDO> eventresourceAllocationsDOS = eventresourceAllocationsService
                .selectList(new EntityWrapper<EventresourceAllocationsDO>()
                        .eq("paper_module", paperTemplateId));
        if (eventresourceAllocationsDOS.size() != 0) {
            return Result.fail("该试卷正在使用中！");
        }

        // 删除模板
//        testPaperTemplateService.updateById(Long.valueOf(paperTemplateId));
        // 逻辑删除关系表的关联
        TestPaperTemplateDO testPaperTemplateDO = new TestPaperTemplateDO();
        testPaperTemplateDO.setState(9);
        EntityWrapper<TestPaperTemplateDO> updateWrapper1 = new EntityWrapper<>();
        updateWrapper1.eq("id", Long.valueOf(paperTemplateId));
        testPaperTemplateService.update(testPaperTemplateDO, updateWrapper1);

        TemplateCertificateDO templateCertificateDO = new TemplateCertificateDO();
        templateCertificateDO.setState(9);
        EntityWrapper<TemplateCertificateDO> updateWrapper = new EntityWrapper<>();
        updateWrapper.eq("paper_template_id", Long.valueOf(paperTemplateId));
        templateCertificateService.update(templateCertificateDO, updateWrapper);

        //删除模板详情表
//        templateDetailsService.delete(new EntityWrapper<TemplateDetailsDO>().eq("tptemplate_id", Long.valueOf(paperTemplateId)));

        return Result.ok();
    }

    @Log("批量删除试卷证书关联")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:templateController:batchRemove")
    public Result<Boolean> remove(@RequestParam("paperTemplateIds[]") String[] paperTemplateIds) {

        //删除模板详情
        for (String paperTemplateId : paperTemplateIds) {
            List<EventresourceAllocationsDO> eventresourceAllocationsDOS = eventresourceAllocationsService
                    .selectList(new EntityWrapper<EventresourceAllocationsDO>()
                            .eq("paper_module", paperTemplateId));
            if (eventresourceAllocationsDOS.size() != 0) {
                return Result.fail("试卷正在使用中！");
            }

            // 逻辑删除关系表的关联
            TestPaperTemplateDO testPaperTemplateDO = new TestPaperTemplateDO();
            testPaperTemplateDO.setState(9);
            EntityWrapper<TestPaperTemplateDO> updateWrapper1 = new EntityWrapper<>();
            updateWrapper1.eq("id", Long.valueOf(paperTemplateId));
            testPaperTemplateService.update(testPaperTemplateDO, updateWrapper1);

            TemplateCertificateDO templateCertificateDO = new TemplateCertificateDO();
            templateCertificateDO.setState(9);
            EntityWrapper<TemplateCertificateDO> updateWrapper = new EntityWrapper<>();
            updateWrapper.eq("paper_template_id", Long.valueOf(paperTemplateId));
            templateCertificateService.update(templateCertificateDO, updateWrapper);

//            // 批量删除模板与关联表
//            testPaperTemplateService.deleteById(Long.valueOf(paperTemplateId));
//            // 删除关系表的关联
//            EntityWrapper<TemplateCertificateDO> deleteWrapper = new EntityWrapper<>();
//            deleteWrapper.eq("paper_template_id", Long.valueOf(paperTemplateId));
//            templateCertificateService.delete(deleteWrapper);
//            //删除模板详情表
//            templateDetailsService.delete(new EntityWrapper<TemplateDetailsDO>().eq("tptemplate_id", Long.valueOf(paperTemplateId)));
        }

        return Result.ok();
    }
}
